package com.atguigu.daijia.common.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;
import org.springframework.boot.autoconfigure.security.oauth2.resource.OAuth2ResourceServerProperties;

import java.util.HashMap;

/**
 * JWT的工具类
 */
public class JwtUtil {
    private static final String SECRET = "lsdj";

    /**
     * 根据userId生成jwt
     *
     * @param userId
     * @return
     */
    public static String generateJWT(String userId) {
        HashMap<String, Object> header = new HashMap<>();
        header.put("alg", "HS256");
        header.put("typ", "JWT");
        return JWT.create().withHeader(header)
                .withClaim("userId", userId)
                .sign(Algorithm.HMAC256(SECRET));

    }

    /**
     * 根据jwt获取userId
     *
     * @param jwt
     * @return
     */
    public static String getCustomerId(String jwt) {
        DecodedJWT decode = JWT.decode(jwt);
        String string = decode.getClaim("userId").asString();
        return string;
    }

    /**
     * 验证jwt格式是否正确
     *
     * @param jwt
     * @return
     */
    public static boolean verifyJWT(String jwt) {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        try {
            DecodedJWT decodedJWT = jwtVerifier.verify(jwt);
        } catch (JWTVerificationException e) {
            return false;
        }
        return true;

    }

}
